package cn.devices.controller;


import cn.devices.entity.TbBorrow;
import cn.devices.entity.TbEvent;
import cn.devices.model.JsonMessage;
import cn.devices.service.TbEventService;
import cn.devices.utils.FileUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.w3c.dom.events.Event;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 告警事件表 前端控制器
 * </p>
 *
 * @author 秋水浮萍
 * @since 2021-02-07
 */
@RestController
@RequestMapping("/tb-event")
public class TbEventController {
    @Value("${load.upload}")
    private String uploadPath;
    @Autowired
    private TbEventService service;

    @PostMapping("eventList")
    public JsonMessage eventList(@RequestParam(defaultValue = "1") int pageIndex,
                                 @RequestParam(defaultValue = "10") int pageSize) {
        JsonMessage message = new JsonMessage();
        String a = "";
        PageInfo<TbEvent> pageInfo = service.eventList(pageIndex, pageSize);
        message.setData(pageInfo);
        return message;
    }

    @PostMapping("eventAdd")
    public JsonMessage eventAdd(String deviceCode, String photo) {
        JsonMessage message = new JsonMessage();
        TbEvent tbEvent = new TbEvent();
        tbEvent.setEventTime(new Date());
        tbEvent.setDeviceCode(deviceCode);
        String path = "";
        try {
            Base64.Decoder decoder = Base64.getMimeDecoder();//注不要使用.getDecoder();
            // 对base64数据进行解码 生成 字节数组，不能直接用Base64.decode（）；进行解密
            byte[] photoimg = decoder.decode(photo);
            for (int i = 0; i < photoimg.length; ++i) {
                if (photoimg[i] < 0) {
                    // 调整异常数据
                    photoimg[i] += 256;
                }
            }
            // byte[] photoimg = Base64.decode(photo);//此处不能用Base64.decode（）方法解密，我调试时用此方法每次解密出的数据都比原数据大  所以用上面的函数进行解密，在网上直接拷贝的，花了好几个小时才找到这个错误（菜鸟不容易啊）
            System.out.println("图片的大小：" + photoimg.length);
            path = uploadPath + File.separator + "back" + deviceCode + ".jpg";
            getFileByBytes(photoimg, uploadPath + File.separator + "event", deviceCode + ".jpg");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            message.setData("失败");
            return message;
        }
        tbEvent.setEventDesc(path);
        service.eventAdd(tbEvent);
        message.setData("归还成功");
        return message;
    }

    public void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
